package com.eightywork.life.adapter;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.eightywork.life.R;
import com.eightywork.life.imageCache.ImageLoader;
import com.eightywork.life.model.Space;
import com.eightywork.life.util.AndroidUtil;

public class ChooseAdapter extends ArrayAdapter<Space> {
	private LayoutInflater mInflater;
	private int mResource = R.layout.item_choose;
	private Context context;
	private int displayWidth;
	private int imageSize;
	private List<String> selectPostion = new ArrayList<String>();
	private ImageLoader imageLoader;

	public ChooseAdapter(Context context, List<Space> list) {
		super(context, 0, list);
		this.context = context;
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		init();
	}

	private void init() {
		displayWidth = ((Activity) context).getWindowManager()
				.getDefaultDisplay().getWidth();
		int spaceWidth = AndroidUtil.dpToPx(16, context);
		imageSize = (displayWidth - 6 * spaceWidth) / 3;
		imageLoader = new ImageLoader(context);
	}

	@Override
	public View getView(final int position, View convertView,
			final ViewGroup parent) {
		View layout = convertView;
		if (layout == null) {
			layout = mInflater.inflate(mResource, parent, false);
		}
		final Space obj = getItem(position);
		ImageView pic = (ImageView) layout.findViewById(R.id.pic);
		imageLoader.DisplayImage(obj.getAvatar(), pic, 0, imageSize, imageSize);

		TextView name = (TextView) layout.findViewById(R.id.name);
		name.setText(obj.getName());

		final ImageView tick = (ImageView) layout.findViewById(R.id.tick);
		tick.setImageResource(R.drawable.tick_a);
		if (!selectPostion.contains(obj.getUid())) {
			tick.setTag("1");
			selectPostion.add(obj.getUid());
			Log.d("Uid", obj.getUid());
		}
		layout.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				if (obj.getVerifyType().equals("4")) {
					return;
				}
				if (((String) tick.getTag()).equals("0")) {
					tick.setImageResource(R.drawable.tick_a);
					tick.setTag("1");
					selectPostion.add(obj.getUid());
				} else {
					tick.setImageResource(R.drawable.tick_b);
					tick.setTag("0");
					selectPostion.remove(obj.getUid());
				}
			}
		});
		return layout;
	}

	public List<String> getSelect() {
		return selectPostion;
	}
}
